<template>
    <view class="cn-component-form">
        <nFormItem key="form_simpleAddress" :tap="() => { disabled ? () => {} : $refs.simpleAddress.open() }" :title="title" :placeholder="placeholder"
            :class_input="class_input" :data.sync="address.data" field="area_code" :tag_data.sync="data" :tag_field="address_field"
            tag_value="请选择" :is_tag_sort_value_title="true" :disabled="true" :text_lr="text_lr?text_lr:'left'" :is_must="is_must">
            <template #right>
                <view class="cuIcon-right"></view>
            </template>
        </nFormItem>
        <simple-address ref="simpleAddress" :pickerValueDefault="address.default" themeColor="#007AFF" @onConfirm="onConfirm"></simple-address>
    </view>
</template>

<script>
    import simpleAddress from '@/components/simple-address/simple-address.vue';
    export default {
        props: ['data', 'field', 'title', 'placeholder', 'class_input', 'disabled', 'text_lr', 'is_must', ],
        components: {
            simpleAddress
        },
        data() {
            let address = {
                default: [0, 0, 0],
                data: {
                    form: {
                        area_code: ''
                    }
                }
            };
            return {
                address: this.$nddyny.object.copy(address),
                addressBak: this.$nddyny.object.copy(address),
            }
        },
        mounted() {
            this.setAddressInfo(this.data.form[this.address_field]);
        },
        computed: {
            address_field() {
                return this.field || 'area_code';
            }
        },
        watch: {
            'data.form'(new_form, old_form) {
                if (new_form[this.address_field] != old_form[this.address_field]) {
                    this.setAddressInfo(this.data.form[this.address_field]);
                }
            }
        },
        methods: {
            onConfirm(e) {
                this.data.form[this.address_field] = e.areaCode;
                this.$emit('update:data', this.data)
                this.setAddressInfo(this.data.form[this.address_field]);
            },
            setAddressInfo(area_code) {
                if (this.$nddyny.string.empty(area_code)) {
                    this.address = this.$nddyny.object.copy(this.addressBak);
                    return;
                }
                let info = this.$nddyny.address.getProvCityAreaInfo(area_code, ' ');
                this.address.default = info.index;
                this.address.data.form.area_code = info.province_city_area_name;
                this.data.formtag[this.address_field] = '';
                this.$emit('update:data', this.data)
            }
        }
    }
</script>
